#!/usr/bin/perl -w

use strict;

use lib "./lib";
use CGI;
use URI::Escape;
use HTML::Template;
use String::Random;
use DB::MailAccounts;
use DB::Users;

&main();

sub main() {
	my $q = new CGI;
	my $template = "../templates/bmark.tmpl";
	my $tmpl = new HTML::Template(filename => $template);

	print $q->header(-type => 'text/html', -charset => 'utf-8');

	my $email = $q->param("e");
    my $secret = $q->param("s");
    if (&validate_email_account($email, $secret)) {
        my $code = &create_user($email);
        if ($code) {
            $tmpl->param(valid => 1);
            $tmpl->param(user => $code);
        }
        else {
            # TODO
        }
    }
    else {
        # TODO
    }

	print $tmpl->output;

}

sub validate_email_account {
    my ($email, $secret) = @_;

    if ($email and $secret) {
        my $db = DB::MailAccounts->new(); 
        my $rh_account = $db->get_account_by_mail_secret($email, $secret);
        if ($rh_account) {
            return 1;
        }
    }
    return 0;
}

sub create_user {
    my ($email) = @_;

    if ($email) {
        my $db = DB::MailAccounts->new();
        my $rh_account = $db->get_account_by_mail($email);
        return undef unless ($rh_account);

        my $user_db = DB::Users->new();
        my $rh_user = $user_db->select_user_by_mail_id($rh_account->{id});
        if ($rh_user) {
            return $rh_user->{code};
        } else {
            my $random = new String::Random;
            my $code = $random->randregex('[0-9a-f]{20}'); 
            $user_db->insert($code, $rh_account->{id}, $rh_account->{mail});
            return $code;
        }
    }

    return undef;
}

